<template>
	<view class="detail">
		<view class="container">
			<view v-if="loading">
				<u-skeleton rows="5" title loading avatar :animate="true"></u-skeleton>
			</view>
			<view v-else>
				<view class="title">
					{{detail.title}}
				</view>
				<view class="userinfo">
					<view class="avatar">
						<image :src="getUserAvatar(detail.user_id)" mode="aspectFill"></image>
					</view>
					<view class="text">
						<view class="name">
							{{getUserNickName(detail.user_id)}}
						</view>
						<view class="time-province">
							
							{{$u.timeFormat(detail.publish_date, 'yyyy年mm月dd日 hh:MM:ss')}} ⚡️ 发布于{{detail.province}}
						</view>
					</view>
				</view>
				<view class="content">
					<u-parse :content="detail.content" :tagStyle="tagStyle"></u-parse>
				</view>
				<view class="like">
					<view @click="like" class="btn" :class="{'active':detail.isLike}">
						<text class="iconfont icon-dianzan"></text>
						<text>{{detail.like_count || '点赞'}}</text>
					</view>
					<view class="users">
						<template v-for="item in likeArr">
							<image :src="getUserAvatar(item.user_id)" mode="aspectFill"></image>
						</template>
					</view>
					<view class="view">
						<text class="num">{{detail.view_count}}</text>人看过
					</view>
				</view>
			</view>
		</view>
		<view class="comment">
			<view v-if="commentList.length==0"style="padding: 50rpx 0 150rpx 0;">
				<u-empty mode="comment" icon="http://cdn.uviewui.com/uview/empty/comment.png">
				</u-empty>
			</view>
			<view v-if="commentList.length" class="content">
				<comment :item="item" v-for="item in commentList" @removeComment="removeComment"></comment>
			</view>
			<commentInput :commentObj="commentObj" @commentEvent="commentEvent"></commentInput>
		</view>
	</view>
</template>

<script>
	const db = uniCloud.database();
	const utilsObj = uniCloud.importObject("utilsObj",{customUI:true});
	import {store} from '../../uni_modules/uni-id-pages/common/store.js'
	import pageJson from '@/pages.json'
	import {getUserNickName,getUserAvatar} from '@/utils/tools.js';
	import comment from '@/components/comment/comment.vue'
	import commentInput from '@/components/comment-input/comment-input.vue'
	export default {
		components:{comment,commentInput},
		data() {
			return {
				artId:'',
				tagStyle:{
					p: 'line-height:1.7em;font-size:16px;padding-bottom:10rpx',
					img:'margin:10px 0'
				},
				loading:true,
				detail:{},
				likeLock:false,
				likeArr:[],
				commentList:[],
				commentObj:{},
			};
		},
		onLoad(options) {
			this.artId = options.id;
			if(!options.id){
				this.errorFunc()
				return
			}
			this.commentObj = {
				article_id:this.artId,
				comment_type:0
			}
			this.getData()
			this.getLikeUsers()
			this.getCommentList()
		},
		methods:{
			getUserNickName,
			getUserAvatar,
			// 错误处理
			errorFunc(){
				uni.showToast({
					title:"获取详情失败",
					icon:"none"
				})
				setTimeout(()=>{
					uni.reLaunch({
						url:"/pages/index/index"
					})
				},1000)
			},
			// 获取详情数据
			getData(){
				let artTemp = db.collection("circle-articles").where(`_id=='${this.artId}'`).getTemp();
				let userTemp = db.collection("uni-id-users").field("_id,nickname,username,avatar_file").getTemp();
				let likeTemp = db.collection("circle-like").where(`article_id=='${this.artId}' && user_id==$cloudEnv_uid`).getTemp();
				let tempArr = [artTemp,userTemp]
				if(store.hasLogin){
					tempArr.push(likeTemp)
				}
				db.collection(...tempArr).get({
					getOne:true
				}).then(res=>{
					console.log('详情',res.result.data)
					if(!res.result.data){
						this.errorFunc()
						return
					}
					let isLike = false;
					if(store.hasLogin){
						isLike = res.result.data._id['circle-like'].length==1;
						res.result.data.isLike = isLike;
					}
					this.detail = res.result.data;
					uni.setNavigationBarTitle({
						title:this.detail.title
					})
					this.loading = false;
					this.updateView()
				}).catch(err=>{
					console.log(err)
					this.errorFunc()
				})
			},
			// 点赞/取消赞
			async like(){
				if(this.likeLock) return uni.showToast({
					title:"操作频繁，请稍后",
					icon:"none"
				})
				if(!store.hasLogin){
					uni,uni.showModal({
						title: '提示',
						content: '您还未登录，是否前往登录页',
						success: res => {
							if(res.confirm){
								uni.navigateTo({
									url:"/"+pageJson.uniIdRouter.loginPage
								})
							}
						}
					});
					return
				}
				this.likeLock = true;
				this.detail.isLike?this.detail.like_count--:this.detail.like_count++;
				this.detail.isLike = !this.detail.isLike;
				this.likeFunc();
			},
			// 点赞操作数据库
			likeFunc(){
				if(!this.detail.isLike){
					uni.showToast({
						title:"取消点赞成功～",
						icon:"none"
					})
					 db.collection("circle-like").where(`article_id=='${this.artId}' && user_id==$cloudEnv_uid`).remove().then(res=>{
						 utilsObj.operation("circle-articles","like_count",this.artId,-1)
					 }).finally(_=>{
						 this.likeLock = false;
					 })
				}else{
					uni.showToast({
						title:"点赞成功～",
						icon:"none"
					})
					db.collection("circle-like").add({
						article_id:this.artId
					}).then(res=>{
						utilsObj.operation("circle-articles","like_count",this.artId,1)
					}).finally(_=>{
						 this.likeLock = false;
					 })
				}
			},
			// 更新浏览数
			updateView(){
				utilsObj.operation("circle-articles","view_count",this.artId,1).then(res=>{
					
				})
			},
			// 获取点赞用户
			async getLikeUsers(){
				let likeTemp = db.collection("circle-like").where(`article_id == '${this.artId}'`).getTemp();
				let userTemp = db.collection("uni-id-users").field("_id,avatar_file").getTemp();
				let res = await db.collection(likeTemp,userTemp).orderBy("like_date desc").get()
				this.likeArr = res.result.data;
			},
			// 获取评论
			async getCommentList(){
				let commentTemp = db.collection("circle-comment").where(`article_id == '${this.artId}' && comment_type==0`).orderBy("comment_date desc").limit(5).getTemp();
				let userTemp = db.collection("uni-id-users").field("_id,username,nickname,avatar_file").getTemp();
				let res = await db.collection(commentTemp,userTemp).get()
				let idArr = res.result.data.map(item=>item._id)
				let replayArr = await db.collection("circle-comment").where({
					reply_comment_id:db.command.in(idArr)
				}).groupBy('reply_comment_id').groupField('count(*) as totalReply').get();
				res.result.data.forEach(item=>{
					let index = replayArr.result.data.findIndex(find=>find.reply_comment_id == item._id)
					if(index>-1){
						item.totalReply = replayArr.result.data[index].totalReply
					}
					
				})
				this.commentList = res.result.data;
				console.log('评论列表:',this.commentList)
			},
			// 评论成功回调
			commentEvent(comment){
				this.commentList.unshift({
					...comment,
					user_id:[{...store.userInfo}]
				})
			},
			// 删除评论回调
			removeComment(id){
				let idx = this.commentList.findIndex(item=>item._id == id)
				this.commentList.splice(idx,1)
				utilsObj.operation("circle-articles","comment_count",this.commentObj.article_id,-1)
			}
		}
	}
</script>

<style lang="scss" scoped>
	.detail{
		background-color: #f8f8f8;
		min-height: calc(100vh - var(--window-top));
		.container{
			padding: 30rpx;
			background: #fff;
			.title{
				font-size: 46rpx;
				color: #333;
				line-height: 1.4em;
				font-weight: bold;
			}
			.userinfo{
				padding: 30rpx 0;
				display: flex;
				align-items: center;
				.avatar{
					width: 60rpx;
					height: 60rpx;
					border-radius: 50%;
					overflow: hidden;
					image{
						width: 100%;
						height: 100%;
					}
				}
				.text{
					padding: 0 20rpx;
					font-size: 28rpx;
					color: #555;
					.time-province{
						font-size: 20rpx;
						color: #999;
					}
				}
			}
			.content{
				
			}
			.like{
				display: flex;
				flex-direction: column;
				align-items: center;
				padding: 80rpx 50rpx;
				.btn{
					width: 260rpx;
					height: 120rpx;
					background-color: #e4e4e4;
					border-radius: 100rpx;
					color: #fff;
					display: flex;
					flex-direction: column;
					align-items: center;
					justify-content: center;
					font-size: 28rpx;
					.iconfont{
						font-size: 50rpx;
					}
					&.active{
						background-color: #0199FE;
					}
				}
			}
			.users{
				margin-top: 30rpx;
				display: flex;
				align-items: center;
				justify-content: center;
				image{
					width: 60rpx;
					height: 60rpx;
					overflow: hidden;
					border-radius: 50%;
				}
			}
			.view{
				margin-top: 30rpx;
				display: flex;
				align-items: center;
				font-size: 26rpx;
				.num{
					color: #0199FE;
				}
			}
		}
		.comment{
			.content{
				padding: 30rpx 30rpx 120rpx 30rpx;
			}
		}
	}
</style>
